package com.roger.homecenterscreen.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.roger.homecenterscreen.data.model.AirQuality
import com.roger.homecenterscreen.data.model.CurrentWeather
import com.roger.homecenterscreen.data.model.DailyForecast
import com.roger.homecenterscreen.data.model.HourlyWeather
import com.roger.homecenterscreen.data.model.WeatherData
import kotlinx.coroutines.delay
import java.util.Calendar

@Composable
fun WeatherDisplay(
    modifier: Modifier = Modifier,
    weatherData: WeatherData? = null
) {
    val currentWeatherData = weatherData ?: getMockWeatherData()
    
    LaunchedEffect(Unit) {
        while (true) {
            // API调用已在ViewModel中处理
            delay(600000) // 每10分钟更新一次
        }
    }
    
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.95f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 城市名称
            Text(
                text = currentWeatherData.location.getDisplayName(),
                fontSize = 22.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF000000),
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            // 当前天气和空气质量组合
            CombinedWeatherSection(
                currentWeather = currentWeatherData.currentWeather,
                airQuality = currentWeatherData.airQuality
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 今天天气总结（最高最低气温等）
            currentWeatherData.todaySummary?.let { todaySummary ->
                TodaySummarySection(
                    todaySummary = todaySummary,
                    currentWeather = currentWeatherData.currentWeather
                )
                Spacer(modifier = Modifier.height(10.dp))
            }
            
            HorizontalDivider()
            Spacer(modifier = Modifier.height(12.dp))
            
            // 今日每小时天气
            val filteredHourlyWeather = filterTodayWeather(currentWeatherData.todayHourly)
            
            Text(
                text = "今日天气",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF000000)
            )
            Spacer(modifier = Modifier.height(8.dp))
            
            if (filteredHourlyWeather.isNotEmpty()) {
                HourlyWeatherSection(filteredHourlyWeather)
            } else {
                Text(
                    text = "今日剩余时段暂无数据",
                    fontSize = 16.sp,
                    color = Color(0xFF424242),
                    modifier = Modifier.padding(8.dp)
                )
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 未来三天天气
            Text(
                text = "未来天气",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF000000)
            )
            Spacer(modifier = Modifier.height(8.dp))
            
            ForecastSection(currentWeatherData.forecast)
        }
    }
}

@Composable
private fun CombinedWeatherSection(
    currentWeather: CurrentWeather,
    airQuality: AirQuality
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceEvenly,
        verticalAlignment = Alignment.Top
    ) {
        // 第一列：温度(上)+天气(下)
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = "${currentWeather.temperature}°",
                fontSize = 42.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF000000)
            )
            Text(
                text = currentWeather.weatherDesc,
                fontSize = 16.sp,
                color = Color(0xFF424242)
            )
        }
        
        // 第二列：体感温度(上)+湿度(中)+风力风向(下)
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.weight(1f)
        ) {
            Text(
                text = "体感 ${currentWeather.feelsLike}°",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = "湿度 ${currentWeather.humidity}%",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = "${currentWeather.windDirection}",
                fontSize = 14.sp,
                color = Color(0xFF424242)
            )
            Text(
                text = "${currentWeather.windSpeed}km/h",
                fontSize = 14.sp,
                color = Color(0xFF424242)
            )
        }
        
        // 第三列：空气质量和AQI(上)+PM2.5(中)+PM10(下)
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.weight(1f)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = airQuality.level,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = getAqiColor(airQuality.aqi)
                )
                Spacer(modifier = Modifier.width(4.dp))
                Text(
                    text = "AQI${airQuality.aqi}",
                    fontSize = 14.sp,
                    color = Color(0xFF424242)
                )
            }
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = "PM2.5: ${airQuality.pm25}",
                fontSize = 14.sp,
                color = Color(0xFF424242)
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = "PM10: ${airQuality.pm10}",
                fontSize = 14.sp,
                color = Color(0xFF424242)
            )
        }
    }
}

@Composable
private fun CurrentWeatherSection(currentWeather: CurrentWeather) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column {
            Text(
                text = "${currentWeather.temperature}°",
                fontSize = 42.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF000000)
            )
            Text(
                text = currentWeather.weatherDesc,
                fontSize = 18.sp,
                color = Color(0xFF424242)
            )
        }
        
        Column(
            horizontalAlignment = Alignment.End
        ) {
            Text(
                text = "体感 ${currentWeather.feelsLike}°",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
            Text(
                text = "湿度 ${currentWeather.humidity}%",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
            Text(
                text = "${currentWeather.windDirection} ${currentWeather.windSpeed}km/h",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
        }
    }
}

@Composable
private fun TodaySummarySection(
    todaySummary: DailyForecast,
    currentWeather: CurrentWeather
) {
    // 紧凑型布局 - 去掉Card，减少间距
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .background(
                Color.Blue.copy(alpha = 0.05f),
                RoundedCornerShape(6.dp)
            )
            .padding(horizontal = 12.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        // 左侧：今天标识 + 温度范围
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = getWeatherEmoji(todaySummary.weatherCode),
                fontSize = 18.sp
            )
            Spacer(modifier = Modifier.width(6.dp))
            Column {
                Text(
                    text = "今天 ${todaySummary.minTemp}°-${todaySummary.maxTemp}°",
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF000000)
                )
                Text(
                    text = todaySummary.weatherDesc,
                    fontSize = 12.sp,
                    color = Color(0xFF424242)
                )
            }
        }
        
        // 右侧：简化的关键信息
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "湿度${currentWeather.humidity}%",
                fontSize = 12.sp,
                color = Color(0xFF424242)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = "UV${currentWeather.uvIndex}",
                fontSize = 12.sp,
                color = Color(0xFF424242)
            )
        }
    }
}

@Composable
private fun AirQualitySection(airQuality: AirQuality) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Column {
            Text(
                text = "空气质量",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF000000)
            )
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = airQuality.level,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = getAqiColor(airQuality.aqi)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "AQI ${airQuality.aqi}",
                    fontSize = 17.sp,
                    color = Color(0xFF424242)
                )
            }
        }
        
        Column(
            horizontalAlignment = Alignment.End
        ) {
            Text(
                text = "PM2.5: ${airQuality.pm25}",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
            Text(
                text = "PM10: ${airQuality.pm10}",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
        }
    }
}

@Composable
private fun HourlyWeatherSection(hourlyWeather: List<HourlyWeather>) {
    LazyRow(
        horizontalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        items(hourlyWeather) { weather ->
            HourlyWeatherItem(weather)
        }
    }
}

@Composable
private fun HourlyWeatherItem(weather: HourlyWeather) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .background(
                Color.Gray.copy(alpha = 0.1f),
                RoundedCornerShape(8.dp)
            )
            .padding(8.dp)
    ) {
        Text(
            text = weather.time,
            fontSize = 15.sp,
            color = Color(0xFF424242)
        )
        Spacer(modifier = Modifier.height(4.dp))
        // 这里可以添加天气图标
        Box(
            modifier = Modifier
                .size(24.dp)
                .background(Color.Gray.copy(alpha = 0.3f), RoundedCornerShape(12.dp)),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = getWeatherEmoji(weather.weatherCode),
                fontSize = 20.sp
            )
        }
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = "${weather.temperature}°",
            fontSize = 17.sp,
            fontWeight = FontWeight.Bold,
            color = Color(0xFF000000)
        )
        Text(
            text = "${weather.precipitation}%",
            fontSize = 13.sp,
            color = Color(0xFF424242)
        )
    }
}

@Composable
private fun ForecastSection(forecast: List<DailyForecast>) {
    Column {
        forecast.forEach { day ->
            ForecastItem(day)
            if (day != forecast.last()) {
                Spacer(modifier = Modifier.height(8.dp))
            }
        }
    }
}

@Composable
private fun ForecastItem(forecast: DailyForecast) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = forecast.dayOfWeek,
                fontSize = 17.sp,
                color = Color(0xFF000000),
                modifier = Modifier.width(40.dp)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = getWeatherEmoji(forecast.weatherCode),
                fontSize = 20.sp
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = forecast.weatherDesc,
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
        }
        
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "${forecast.precipitation}%",
                fontSize = 15.sp,
                color = Color(0xFF424242)
            )
            Spacer(modifier = Modifier.width(16.dp))
            Text(
                text = "${forecast.minTemp}°/${forecast.maxTemp}°",
                fontSize = 17.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF000000)
            )
        }
    }
}

private fun getAqiColor(aqi: Int): Color {
    return when {
        aqi <= 50 -> Color(0xFF4CAF50)  // 优
        aqi <= 100 -> Color(0xFFFFEB3B) // 良
        aqi <= 150 -> Color(0xFFFF9800) // 轻度污染
        aqi <= 200 -> Color(0xFFF44336) // 中度污染
        aqi <= 300 -> Color(0xFF9C27B0) // 重度污染
        else -> Color(0xFF795548)        // 严重污染
    }
}

private fun filterTodayWeather(hourlyWeather: List<HourlyWeather>): List<HourlyWeather> {
    val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
    
    return hourlyWeather.filter { weather ->
        // 解析时间字符串，获取小时
        val hour = try {
            weather.time.substring(0, 2).toInt()
        } catch (e: Exception) {
            0
        }
        // 只显示当前时间之后的天气
        hour >= currentHour
    }
}

private fun getWeatherEmoji(weatherCode: String): String {
    return when (weatherCode) {
        "sunny" -> "☀️"
        "cloudy" -> "☁️"
        "partly_cloudy" -> "⛅"
        "rainy" -> "🌧️"
        "snowy" -> "❄️"
        "thunderstorm" -> "⛈️"
        "foggy" -> "🌫️"
        else -> "☀️"
    }
}

// 生成今日小时天气数据
private fun generateHourlyWeatherData(): List<HourlyWeather> {
    val hourlyData = mutableListOf<HourlyWeather>()
    val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
    
    // 生成今天从当前时间开始的小时天气数据
    for (i in 0 until 12) {
        val hour = (currentHour + i) % 24
        val timeString = String.format("%02d:00", hour)
        
        // 模拟不同时段的温度和天气
        val temperature = when (hour) {
            in 6..9 -> 18 + (hour - 6) * 2  // 早晨逐渐升温
            in 10..14 -> 24 + (hour - 10)  // 中午最热
            in 15..18 -> 28 - (hour - 15)  // 下午逐渐降温
            in 19..23 -> 22 - (hour - 19)  // 晚上继续降温
            else -> 16 + hour / 2  // 深夜到凌晨
        }
        
        val (weatherCode, weatherDesc, precipitation) = when {
            hour in 14..16 -> Triple("rainy", "小雨", 70)
            hour in 7..11 -> Triple("sunny", "晴", 10)
            hour in 17..19 -> Triple("partly_cloudy", "多云", 30)
            else -> Triple("cloudy", "阴", 40)
        }
        
        hourlyData.add(
            HourlyWeather(
                time = timeString,
                temperature = temperature,
                weatherCode = weatherCode,
                weatherDesc = weatherDesc,
                icon = weatherCode,
                precipitation = precipitation
            )
        )
    }
    
    return hourlyData
}

// 模拟天气数据
private fun getMockWeatherData(): WeatherData {
    return WeatherData(
        currentWeather = CurrentWeather(
            temperature = 22,
            feelsLike = 25,
            humidity = 65,
            pressure = 1013,
            visibility = 10,
            uvIndex = 5,
            windSpeed = 12,
            windDirection = "东南风",
            weatherCode = "partly_cloudy",
            weatherDesc = "多云",
            icon = "partly_cloudy"
        ),
        todayHourly = generateHourlyWeatherData(),
        todaySummary = DailyForecast(
            date = "12-25",
            dayOfWeek = "今天",
            minTemp = 15,
            maxTemp = 28,
            weatherCode = "partly_cloudy",
            weatherDesc = "多云转晴",
            icon = "partly_cloudy",
            precipitation = 20
        ),
        forecast = listOf(
            DailyForecast("12-26", "明天", 18, 25, "partly_cloudy", "多云", "partly_cloudy", 30),
            DailyForecast("12-27", "后天", 16, 22, "rainy", "小雨", "rainy", 80),
            DailyForecast("12-28", "周六", 19, 26, "sunny", "晴", "sunny", 10)
        ),
        airQuality = AirQuality(
            aqi = 85,
            level = "良",
            pm25 = 35,
            pm10 = 55,
            so2 = 12,
            no2 = 25,
            co = 0.8f,
            o3 = 45
        )
    )
} 